using System;
using System.IO;
using System.Windows.Forms;
using System.Windows.Input;



namespace ScriptEase.Shell.Commands
{
    internal class ProjectOpenCommand : ICommand
    {
        private readonly ShellViewModel _viewViewModel;



        public ProjectOpenCommand(ShellViewModel viewViewModel)
        {
            _viewViewModel = viewViewModel;
        }



        public void Execute(object view)
        {
            string mostRecentProjectName = MruList.Current.MostRecent;

            string dir =
                mostRecentProjectName != null && Directory.Exists(Path.GetDirectoryName(mostRecentProjectName))
                     ? Path.GetDirectoryName(mostRecentProjectName) : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            OpenFileDialog d = new OpenFileDialog
                {
                    CheckFileExists = true,
                    DefaultExt = ".seproj",
                    Filter = @"ScriptEase Project|*.seproj" + "|All files (*.*)|*.*",
                    Title = @"ScriptEase Project",
                    Multiselect = false,
                    RestoreDirectory = true,
                    InitialDirectory = dir,
                    FileName = Path.GetFileName(mostRecentProjectName),
                    AutoUpgradeEnabled = true
                };
            DialogResult result = d.ShowDialog(view as Form);
            if (result == DialogResult.OK)
            {
                _viewViewModel.CloseProject();
                _viewViewModel.OpenProject(d.FileName);
            }
        }



        public bool CanExecute(object parameter)
        {
            return _viewViewModel.ProjectLoadStatus != ProjectStatus.Connecting;
        }



        public event EventHandler CanExecuteChanged;
    }
}